package com.odontosis.view.servico.cadastro.paciente;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.commons.lang.StringUtils;

import com.odontosis.entidade.Paciente;
import com.odontosis.service.PacienteService;
import com.odontosis.util.StringUtilsOdontosis;
import com.odontosis.view.OdontosisAction;
import com.odontosis.view.cadastro.paciente.FormCadastroPaciente;

public class AcaoCadastroPaciente extends OdontosisAction<PacienteService> {

	
	public ActionForward pesquisar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormCadastroPaciente formulario = (FormCadastroPaciente) form;
		
		
		realizarPesquisa(request, formulario);
		return mapping.getInputForward();
    }

	private void realizarPesquisa(HttpServletRequest request,
			FormCadastroPaciente formulario) {
		Collection<Paciente> colecao = null;
		if(StringUtilsOdontosis.isVazia(formulario.getNomePaciente()) && StringUtilsOdontosis.isVazia(formulario.getNumeroPaciente()) && !formulario.isComIpsm()){
			colecao = service.findAll();
		}else{
			colecao = service.pesquisarPorNomeECodigo(formulario.getNumeroPaciente(), formulario.getNomePaciente(),formulario.isComIpsm());
		}
		request.setAttribute("colecao", colecao);
	}

	public ActionForward onInciar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse arg3) throws Exception {
		FormCadastroPaciente formulario = (FormCadastroPaciente) form;
		realizarPesquisa(request, formulario);
		return mapping.getInputForward();
	}

	public ActionForward onDeletar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormCadastroPaciente formulario = (FormCadastroPaciente) form;
		service.excluirLogicamente(service.load(new Long(formulario.getExcluido())));
		formulario.setMetodo(null);
		return pesquisar(mapping, form, request, response);
	}

	@Override
	public ActionForward execute(ActionMapping arg0, ActionForm form,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		FormCadastroPaciente formulario = (FormCadastroPaciente) form;
		if(StringUtils.isEmpty(formulario.getMetodo()))
		{
			return onInciar(arg0, form, arg2, arg3);
		}else if(formulario.getMetodo().equals("deletar")){
			return onDeletar(arg0, form, arg2, arg3);
		}
		return onInciar(arg0, form, arg2, arg3);
	}

}
